package com.wisdom.client.cluster.lb;

import com.wisdom.client.cluster.ClientLoadBalanceStrategy;
import com.wisdom.core.annotation.WisdomLoadBalance;
import com.wisdom.core.enums.LoadBalanceStrategy;
import com.wisdom.core.provider.ServiceProvider;
import org.apache.commons.lang3.RandomUtils;

import java.util.LinkedList;
import java.util.List;

/**
 * @description: <加权随机负载均衡算法>
 * @author: Leo
 * @date: 2021-08-29 17:04
 */
@WisdomLoadBalance(strategy = LoadBalanceStrategy.WEIGHT_RANDOM)
public class WeightRandomClientLoadBalance implements ClientLoadBalanceStrategy {


    @Override
    public ServiceProvider getProvider(List<? extends ServiceProvider> serviceProviders) {

        List<ServiceProvider> newServiceProviders = new LinkedList<>();
        double allWeight = serviceProviders.stream()
                .map(ServiceProvider::getWeight)
                .reduce(Double::sum)
                .orElse(serviceProviders.size() * 1.0);

        serviceProviders.forEach(serviceProvider -> {
                    double weight = serviceProvider.getWeight();
                    int proportion;
                    if (allWeight % weight == 0) {
                        proportion = (int) (allWeight / weight);
                    } else {
                        proportion = (int) (allWeight / weight) + 1;
                    }
                    for (int i = 0; i < proportion; i++) {
                        newServiceProviders.add(serviceProvider);
                    }
                });

        int index = RandomUtils.nextInt(0, newServiceProviders.size());
        return newServiceProviders.get(index);
    }
}
